<template>
  <div>
    <!--卡片-->
    <el-card class="box-card">
      <!-- 搜索与添加区域 -->
      <el-button v-hasPermi="['admin','product:brand:add']" type="primary" small style="margin:10px" size="mini" icon="el-icon-plus" @click="addBtn()">新增
      </el-button>
      <!--表格-->
      <el-table :data="listForm" stripe border style="width: 100%">
        <el-table-column prop="brandId" header-align="center" align="center" label="品牌id" width="80" />
        <el-table-column prop="name" header-align="center" align="center" label="品牌名" width="100" />
        <el-table-column prop="logo" header-align="center" align="center" label="品牌logo地址">
          <template slot-scope="scope">
            <img referrer="no-referrer" :src="scope.row.logo" style="width: 100px; height: 80px">
          </template>
        </el-table-column>
        <el-table-column
          prop="descript"
          header-align="center"
          align="center"
          label="介绍"
        />
        <el-table-column label="状态" width="80">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.showStatus"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :active-value="1"
              :inactive-value="0"
              @change="userStateChanged(scope.row)"
            /></template>
        </el-table-column>
        <el-table-column prop="firstLetter" header-align="center" align="center" label="检索首字母" width="100" />
        <el-table-column prop="sort" header-align="center" align="center" label="排序" width="80" />
        <!--操作-->
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button v-hasPermi="['admin','product:brand:relevance']" type="text" size="mini" @click="relevanceBtn(scope.row.brandId)">关联分类</el-button>
            <el-button v-hasPermi="['admin','product:brand:edit']" type="text" size="mini" @click="editBtn(scope.row.brandId)">编辑</el-button>
            <el-button v-hasPermi="['admin','product:brand:del']" type="text" size="mini" @click="delBtn(scope.row.brandId)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!--分页区域-->
      <el-pagination
        background
        :current-page="pageNumber"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />

    </el-card>

    <!--添加对话框-->
    <el-dialog title="添加" :close-on-click-modal="false" :visible.sync="addDialogVisible" width="580px" @close="addHandleClose">
      <span>
        <el-form ref="addFormRef" :model="addForm" :rules="addFormRules" label-width="100px">
          <el-form-item label="品牌名" prop="name">
            <el-input v-model="addForm.name" />
          </el-form-item>
          <el-form-item label="品牌logo地址" prop="logo">
            <el-upload
              :data="dataObj"
              class="upload-demo"
              action="http://mtzx-zx.oss-cn-shanghai.aliyuncs.com"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :before-upload="beforeUpload"
              :on-success="handleUploadSuccess"
              multiple
              :limit="3"
              :file-list="fileList"
              list-type="picture"
            >

              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>

          </el-form-item>
          <el-form-item label="介绍" prop="descript">
            <el-input v-model="addForm.descript" />
          </el-form-item>
          <el-form-item label="显示状态" prop="showStatus">
            <el-radio-group v-model="addForm.showStatus" size="mini">
              <el-radio-button :label="1">是</el-radio-button>
              <el-radio-button :label="0">否</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="检索首字母" prop="firstLetter">
            <el-input v-model="addForm.firstLetter" />
          </el-form-item>
          <el-form-item label="排序" prop="sort">
            <el-input-number
              v-model.number="addForm.sort"
              :min="1"
              :max="999"
              controls-position="right"
              style="width: 178px;"
            />
          </el-form-item>
        </el-form>
        <!--底部区域-->
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelAdd()">取 消</el-button>
        <el-button type="primary" @click="addClick">确 定</el-button>
      </span>
    </el-dialog>

    <!--编辑对话框-->
    <el-dialog title="编辑" :close-on-click-modal="false" :visible.sync="editDialogVisible" width="580px" @close="editHandleClose">
      <span>
        <el-form ref="editFormRef" :model="editForm" label-width="100px">
          <el-form-item label="品牌名" prop="name">
            <el-input v-model="editForm.name" />
          </el-form-item>
          <el-form-item label="品牌logo地址" prop="logo">
            <el-input v-model="editForm.logo" />
          </el-form-item>
          <el-form-item label="介绍" prop="descript">
            <el-input v-model="editForm.descript" />
          </el-form-item>
          <el-form-item label="显示状态" prop="showStatus">
            <el-radio-group v-model="editForm.showStatus" size="mini">
              <el-radio-button :label="1">是</el-radio-button>
              <el-radio-button :label="0">否</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="检索首字母" prop="firstLetter">
            <el-input v-model="editForm.firstLetter" />
          </el-form-item>
          <el-form-item label="排序" prop="sort">
            <el-input-number
              v-model.number="editForm.sort"
              :min="1"
              :max="999"
              controls-position="right"
              style="width: 178px;"
            />
          </el-form-item>

        </el-form>
        <!--底部区域-->
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editClick">确 定</el-button>
      </span>
    </el-dialog>

    <!--关联对话框-->
    <el-dialog title="关联分类" :close-on-click-modal="false" :visible.sync="relevanceDialogVisible" width="580px">
      <span>
        <el-popover
          v-model="addRelevanceDialogVisible"
          placement="right"
          width="400"
          trigger="click"
        >
          <el-cascader
            v-model="catelogIds"
            placeholder="试试搜索：手机"
            filterable
            :options="catgoretyTree"
            :props="defaultProps"
            style="width: 350px"
          />
          <div style="text-align: right; margin: 10px">
            <el-button size="mini" type="text" @click="addRelevanceDialogVisible = false">取消</el-button>
            <el-button type="primary" size="mini" @click="addRelevanceClick()">确定</el-button>
          </div>
          <el-button slot="reference" type="primary" small style="margin:10px" size="mini" icon="el-icon-plus" @click="addRelevanceBtn()">关联
          </el-button>
        </el-popover>
        <!--表格-->
        <el-table :data="relevanceForm" stripe border style="width: 100%">
          <el-table-column
            prop="brandName"
            header-align="center"
            align="center"
            label="品牌名"
          />
          <el-table-column
            prop="catelogName"
            header-align="center"
            align="center"
            label="分类名"
          />
          <!--操作-->
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-tooltip :enterable="false" effect="dark" content="删除" placement="top">
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="delcategorybrandrelationBtn(scope.row.id)" />
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <!--底部区域-->
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="relevanceDialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { tree } from '@/api/product/category'
import { add, edit, del, getBrand, listBrand } from '@/api/product/brand'
import { addcategorybrandrelation, delcategorybrandrelation, listAttrAttrgroupRelation } from '@/api/product/categorybrandrelation'
import { ossSignature } from '@/api/thirdparty/uploadfile'
import { getUUID } from '@/utils/syyo'

export default {
  name: 'Brand',
  data() {
    return {
      relevanceDialogVisible: false,
      addRelevanceDialogVisible: false,
      addDialogVisible: false,
      editDialogVisible: false,
      pageNumber: 1,
      pageSize: 10,
      total: 0,
      currentBrandId: 0,
      catelogIds: [],
      fileList: [],
      relevanceForm: [],
      listForm: [],
      catgoretyTree: [],
      defaultProps: {
        children: 'children',
        label: 'name',
        value: 'catId'
      },
      dataObj: {
        policy: '',
        signature: '',
        ossaccessKeyId: '',
        key: '',
        dir: '',
        host: ''
      },
      addRelevanceForm: {
        brandId: '',
        name: '',
        logo: ''
      },
      addForm: {
        brandId: '',
        name: '',
        logo: '',
        descript: '',
        showStatus: 1,
        firstLetter: '',
        sort: ''
      },
      editForm: {},
      addFormRules: {
        name: [
          { required: true, message: '请输入品牌名', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '品牌名的长度在3~10个字符之间',
            trigger: 'blur'
          }
        ],
        descript: [
          { required: true, message: '请输入介绍', trigger: 'blur' }

        ],
        showStatus: [
          { required: true, message: '请输入显示状态[0-不显示；1-显示]', trigger: 'blur' }

        ],
        firstLetter: [
          { required: true, message: '请输入检索首字母', trigger: 'blur' }

        ],
        sort: [
          { required: true, message: '请输入排序', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    // 初始化列表
    this.initListBrand()
  },

  methods: {
    beforeUpload(file) {
      const _self = this
      return new Promise((resolve, reject) => {
        ossSignature().then(res => {
          _self.dataObj.policy = res.data.policy
          _self.dataObj.signature = res.data.signature
          _self.dataObj.ossaccessKeyId = res.data.accessid
          _self.dataObj.key = res.data.dir + getUUID() + '_' + file.name
          _self.dataObj.dir = res.data.dir
          _self.dataObj.host = res.data.host
          resolve(true)
        }).catch(err => {
          reject(err)
        })
      })
    },
    handleUploadSuccess(res, file) {
      const obj = {
        name: file.name,
        url: 'https://mtzx-zx.oss-cn-shanghai.aliyuncs.com/' + this.dataObj.key
      }
      this.fileList.push(obj)
      this.addForm.logo = 'https://mtzx-zx.oss-cn-shanghai.aliyuncs.com/' + this.dataObj.key
    },
    handleRemove(file, fileList) {

    },
    handlePreview(file) {

    },
    // 添加按钮
    addBtn() {
      this.addDialogVisible = true
    },

    // 确认添加
    addClick() {
      this.$refs.addFormRef.validate(valid => {
        if (!valid) return
        add(this.addForm).then(res => {
          if (res.code === 20000) {
            this.$message.success(res.message)
            // 刷新数据
            this.initListBrand()
          }
          // 关闭对话框
          this.addDialogVisible = false
        })
      })
    },

    cancelAdd() {
      this.addDialogVisible = false
      this.fileList = []
    },

    // 修改状态
    userStateChanged(row) {
      const data = {
        brandId: row.brandId,
        showStatus: row.showStatus
      }
      edit(data).then(res => {
        if (res.code === 20000) {
          this.$message.success(res.message)
          // 刷新数据
          this.initListBrand()
        }
      })
    },

    // 编辑按钮
    editBtn(id) {
      this.editDialogVisible = true
      getBrand(id).then(res => {
        if (res.code === 20000) {
          this.editForm = res.data
        }
      })
    },

    // 确认编辑
    editClick() {
      this.$refs.editFormRef.validate(valid => {
        if (!valid) return
        edit(this.editForm).then(res => {
          if (res.code === 20000) {
            this.$message.success(res.message)
            // 刷新数据
            this.initListBrand()
          }
          // 关闭对话框
          this.editDialogVisible = false
        })
      })
    },

    // 删除按钮
    delBtn(id) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 确认操作
        del(id).then(res => {
          if (res.code === 20000) {
            this.$message.success(res.message)
            // 刷新数据
            this.initListBrand()
          }
        })
      })
    },

    // 关联按钮
    relevanceBtn(brandId) {
      this.relevanceDialogVisible = true
      this.currentBrandId = brandId
      this.initlistAttrAttrgroupRelation()
    },
    addRelevanceClick() {
      this.addRelevanceDialogVisible = false
      // 添加新的分类
      // 查询当前分类列表
      if (this.catelogIds.length > 0) {
        const params = {
          brandId: this.currentBrandId,
          catelogId: this.catelogIds[this.catelogIds.length - 1]
        }
        addcategorybrandrelation(params).then(res => {
          if (res.code === 20000) {
          // 添加成功，查询当前分类
            this.initlistAttrAttrgroupRelation()
            this.$message.success(res.message)
          }
        })
      }
    },

    addRelevanceBtn() {
      tree().then(res => {
        this.catgoretyTree = res.data
      })
    },
    // 删除关联按钮
    delcategorybrandrelationBtn(id) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 确认操作
        delcategorybrandrelation(id).then(res => {
          if (res.code === 20000) {
            this.initlistAttrAttrgroupRelation()
            this.$message.success(res.message)
            // 刷新数据
          }
        })
      })
    },

    // 监听当前页的事件
    handleCurrentChange(pageIndex) {
      this.pageNumber = pageIndex
      this.initListBrand()
    },

    // 监听当前页的条数事件
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.initListBrand()
    },

    // 监听添加对话框的关闭事件，重置表单内容
    addHandleClose() {
      this.$refs.addFormRef.resetFields()
    },

    // 监听编辑对话框的关闭事件,重置表单内容
    editHandleClose() {
      this.$refs.editFormRef.resetFields()
    },

    // 初始化数据
    initListBrand() {
      const params = {
        pageNum: this.pageNumber,
        pageSize: this.pageSize
      }
      listBrand(params).then(res => {
        this.listForm = res.data.records
        this.total = res.data.total
        this.pageNum = res.data.current
      })
    },

    // 查询品牌关联的分类
    initlistAttrAttrgroupRelation() {
      const params = {
        brandId: this.currentBrandId
      }
      listAttrAttrgroupRelation(params).then(res => {
        if (res.code === 20000) {
          this.relevanceForm = res.data
        }
      })
    }
  }
}
</script>

<style scoped>
.avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
